package com.huajx.tb.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.huajx.util.convert.Convert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.huajx.core.handler.HandlerAdapter;
import com.huajx.core.message.RequestMessage;
import com.huajx.core.message.ResponseMessage;
import com.huajx.core.util.MessageKit;
import com.huajx.tb.dto.NengLongMessage;

/**
 * 上传通话话单语法(由考勤机发给翼校通平台) [05]
 */
public class CallAccountHandler extends AbstractNengLongHandler {
    protected final Logger logger = LoggerFactory.getLogger(CallAccountHandler.class);
    public final static HandlerAdapter me = new CallAccountHandler();
    private final static String controllerKey = "/di/call/account";//getServerUrl();

    @Override
    public ResponseMessage handler(RequestMessage request) {
        NengLongMessage dto = getMessage(request.getMessage());

        byte[] bytes = dto.getBody();
        int len = bytes.length;
        int packageLength = dto.getPackageLength();
        String body = MessageKit.getStr(bytes, 32, packageLength);
        String cardId = MessageKit.getStr(bytes, 32, 20).trim();

//		String strAll = new String (bytes);
        logger.info("完整的命令行,{}", new String(bytes));
//		String body =strAll.substring(32,strAll.length()-2);
//		String carId = body.substring(0,20);
//		if(StrUtil.isBlank(cardId)) {
//
//		}
//		if(carId.length()==20){
//			carId=carId.replaceFirst("^0*", "").trim();
//		}
        String date = body.substring(20, 32);
        String length = body.substring(32, 38);
        String phone = body.substring(38, packageLength - 2);
        if (phone.length() == 16) {
            phone = phone.replaceFirst("^0*", "").trim();
        }
        String schoolCode = dto.getDeviceId().substring(0, 9);
        Map<String, String> paras = new HashMap<>();
        paras.put("content", MessageKit.bytesToString(bytes));
        paras.put("schoolId", schoolCode);
        paras.put("sn", dto.getDeviceId());
        paras.put("code", cardId);
        paras.put("length", length);
        paras.put("date", date);
        paras.put("phone", phone);
        logger.info("解析body：{}", body);

//        System.out.println("校验和"+MessageKit.checksum("013047220073         "));
        // 处理卡点数据
        // asyncPost(controllerKey, paras, bytes, request, null);
        // 处理卡点数据
        try {
            Object obj = post(controllerKey, paras);
            render(request.getSession(), bytes, Convert.toStr(obj));
        } catch (IOException e) {
            logger.warn("话单上传服务器异常", e);
            render(request.getSession(), dto, "ERROR");
        }
        return null;
    }
//    /**
//     * 应答语法
//     * 后台拼接好包长+功能号+包体+较验码
//     *
//     * @param session
//     * @param bytes
//     * @param content
//     */
//    protected void render(IoSession session, NengLongMessage dto, String content) {
//    	 byte[] bytes = dto.getBody();
//         String m = MessageKit.getStr(bytes, 3, 23);
//         int len = null == content ? 2 : content.length() + 2;
//         String lenHex = MessageKit.intToHex(len, '0', 4);
//         String command = dto.getCommand();
//         String checksum = MessageKit.checksum(command + content);
//         StringBuilder sb = new StringBuilder();
//         sb.append(RETURN_COMMAND).append(m).append(lenHex).append(command).append(content).append(checksum);
//         logger.info("返回命令, {}", sb);
//         try {
// 			session.write(sb.toString().getBytes("GB2312"));
//		 } catch (UnsupportedEncodingException e) {
// 			// TODO Auto-generated catch block
// 			e.printStackTrace();
// 		}
//    }
//
//    protected void render(IoSession session, byte[] bytes, String content) {
//        String m = MessageKit.getStr(bytes, 3, 23);
//        StringBuilder sb = new StringBuilder();
//        sb.append(RETURN_COMMAND).append(m).append(content);
//        logger.info("返回命令, {}", sb);
//        try {
//			session.write(sb.toString().getBytes("GB2312"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//    }
}
